import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:raze/potions/raze_constant.dart';
import 'package:raze/potions/spatial_alchemy.dart';
import 'package:video_player/video_player.dart';

/// 视频播放页面
class VideoPlayerRealms extends StatefulWidget {
  const VideoPlayerRealms({super.key});

  @override
  State<VideoPlayerRealms> createState() => _VideoPlayerRealmsState();
}

class _VideoPlayerRealmsState extends State<VideoPlayerRealms> {
  VideoPlayerController? _videoPlayerController;
  bool _isInitialized = false;
  bool _hasError = false;

  @override
  void initState() {
    super.initState();
    _initializeVideo();
  }

  @override
  void dispose() {
    _videoPlayerController?.dispose();
    super.dispose();
  }

  /// 初始化视频播放器
  Future<void> _initializeVideo() async {
    try {
      final videoPath = Get.parameters['videoPath'] ?? '';
      if (videoPath.isEmpty) {
        setState(() {
          _hasError = true;
        });
        return;
      }

      VideoPlayerController controller;

      // 判断是 assets 资源还是本地文件
      if (videoPath.startsWith('assets/')) {
        // assets 资源
        controller = VideoPlayerController.asset(videoPath);
      } else if (videoPath.startsWith('/')) {
        // 本地文件路径
        controller = VideoPlayerController.file(File(videoPath));
      } else {
        // 默认当作 assets 处理
        controller = VideoPlayerController.asset(videoPath);
      }

      await controller.initialize();
      controller.setLooping(true);
      controller.play();

      if (mounted) {
        setState(() {
          _videoPlayerController = controller;
          _isInitialized = true;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _hasError = true;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: RazeConstants.black,
      body: SafeArea(
        child: Stack(
          children: [
            // 视频播放器（全屏背景）
            _buildVideoPlayer(),
            // 返回按钮
            _buildBackButton(),
          ],
        ),
      ),
    );
  }

  /// 构建视频播放器
  Widget _buildVideoPlayer() {
    if (_hasError) {
      return Center(
        child:
            Text('Failed to load video')
                .applyTypeSize(16.sp)
                .applyTypeColor(RazeConstants.white)
                .applyNotoSans(),
      );
    }

    if (!_isInitialized || _videoPlayerController == null) {
      return const Center(
        child: CircularProgressIndicator(color: RazeConstants.white),
      );
    }

    return SizedBox.expand(
      child: FittedBox(
        fit: BoxFit.cover,
        child: SizedBox(
          width: _videoPlayerController!.value.size.width,
          height: _videoPlayerController!.value.size.height,
          child: VideoPlayer(_videoPlayerController!),
        ),
      ),
    );
  }

  /// 构建返回按钮
  Widget _buildBackButton() {
    return Positioned(
      top: 16.h,
      left: 16.w,
      child: Container(
            width: 30.w,
            height: 30.w,
            decoration: BoxDecoration(
              color: RazeConstants.background,
              borderRadius: BorderRadius.circular(8.r),
              border: Border.all(color: RazeConstants.black, width: 1.5.w),
            ),
            child: Icon(
              Icons.chevron_left_rounded,
              size: 24.sp,
              color: RazeConstants.black,
            ),
          )
          .withRightBottomShadow(thickness: 1)
          .withTouchResonance(onTap: () => Get.back()),
    );
  }
}
